#include <my_header.h>


// 服务端启动需要的信息初始化
int getValidStr(char *input, char *str) {
      char *p;
      char s[] = {' ', '\n'};
      p = strtok(input, s);
      p = strtok(NULL, s);
      p = strtok(NULL, s);
      strcpy(str, p);
      return 0;
}

int getServerConf(char *fileconf, char *ip, char *port, int *pworkernum) {
      FILE *pconf = fopen(fileconf, "r");
      ERROR_CHECK(pconf, NULL, "open conf file failed");
      char buf[128] = {0};
      fgets(buf, sizeof(buf), pconf);
      getValidStr(buf, ip);
      bzero(buf, sizeof(buf));
      fgets(buf, sizeof(buf), pconf);
      getValidStr(buf, port);
      bzero(buf, sizeof(buf));
      fgets(buf, sizeof(buf), pconf);
      char num[10] = {0};
      getValidStr(buf, num);
      *pworkernum = atoi(num);
      fclose(pconf);
      return 0;
}


// 用户登录
// 生成salt
int createSaltValue(char *salt) {
    srand(time(NULL));
    char element[65] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
    for (int i = 0; i < 20; i++) {
        salt[i + 3] = element[rand() % 64];
    }
    salt[0] = '$';
    salt[1] = '6';
    salt[2] = '$';
    salt[23] = '$';
    return 0;
}

// 计算密文
int calEncryptedPassword(char *key, char *salt, char *encryptedPassword) {
    strcat(encryptedPassword, salt);
    strcat(encryptedPassword, crypt(key, salt));
    return 0;
}

// 和库里的密码对比判断
int isRightPassword(char *username, char *password) {
    struct spwd *userinfo = getspnam(username);
    ERROR_CHECK(userinfo, NULL, "getspnam");
    char *rightPassword = userinfo->sp_pwdp;
    /* printf("%s\n", rightPassword); */
    if (strcmp(rightPassword, password) == 0) {
        return 1;
    } else {
        return 0;
    }
}

/* int main(void) { */
/*     char salt[]="$6$yKUuZc3.zF3o2B0J$"; */
/*     char password[] = "123"; */
/*     char encryptedPassword[128] = {0}; */
/*     calEncryptedPassword(password, salt, encryptedPassword); */
/*     printf("%s\n", encryptedPassword); */
/*     int res = isRightPassword("zyn", "123"); */
/*     printf("%d\n", res); */
/*     return 0; */
/* } */
